package cn.com.cetccst.appstore.ui.activity;

import static cn.com.cetccst.appstore.tools.AppAction.buttonClick;

import android.app.AlertDialog;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.text.DecimalFormat;
import java.util.ArrayList;

import cn.com.cetccst.appstore.BR;
import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.database.AppStoreRepository;
import cn.com.cetccst.appstore.database.model.AppModel;
import cn.com.cetccst.appstore.databinding.ActivityAppDetailBinding;
import cn.com.cetccst.appstore.databinding.AppDetailScreenshotBinding;
import cn.com.cetccst.appstore.manager.ApkDownloadManager;
import cn.com.cetccst.appstore.tools.CommonAlert;
import cn.com.cetccst.appstore.ui.activity.viewmodel.AppDetailViewModel;
import cn.com.cetccst.tools.pm.AppPackage;
import cn.com.cetccst.tools.ui.ThreadSafeToast;
import cn.com.cetccst.uicomponents.binding.app.DataBindingConfig;
import cn.com.cetccst.uicomponents.binding.recyclerview.SimpleDataBindingAdapter;

public class AppDetailActivity extends BaseActivity<ActivityAppDetailBinding> {

    private static final String TAG = "AppDetailActivity";
    public static final String EXTRA_APP_ID = "app_key";
    private AppDetailViewModel viewModel;
    private AlertDialog dialog;
    private String appId;

    @Override
    protected void initViewModel() {
        viewModel = getActivityScopeViewModel(AppDetailViewModel.class);
        appId = getIntent().getStringExtra(EXTRA_APP_ID);
        viewModel.appDetail = AppStoreRepository.getInstance().loadAppByAppId(appId);
        viewModel.appDetail.observe(this, appModel -> viewModel.requestPublisher());
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        return new DataBindingConfig(R.layout.activity_app_detail, BR.viewModel, viewModel)
                .addBindingParam(BR.click, new ClickProxy())
                .addBindingParam(BR.adapter, new ScreenshotAdapter())
                .addBindingParam(BR.decimalFormat, new DecimalFormat("#,###"));
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestWithProgress(appId);
    }

    private void createProgressDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_progress_dialog, null, false);
        dialog = new AlertDialog.Builder(this).setView(view).create();
        dialog.setCancelable(false);
        dialog.show();
    }

    private void requestWithProgress(String appId) {

        if (TextUtils.isEmpty(appId)) {
            ThreadSafeToast.show(R.string.store_appid_error, Toast.LENGTH_SHORT);
            finish();
            return;
        }

        requestAppDetail(appId);
    }

    private void requestAppDetail(String appId) {
        createProgressDialog();
        viewModel.requestAppDetail(this, appId, success -> {
            if (!isFinishing() && dialog.isShowing()) {
                dialog.dismiss();
            }
            if (!success)
                getBinding().loadFailureTip.setText(Html.fromHtml(getString(R.string.store_app_detail_load_failed), Html.FROM_HTML_MODE_COMPACT));
            else {

                viewModel.appDetail.observe(this, new Observer<>() {
                    @Override
                    public void onChanged(AppModel appModel) {
                        //TODO 这是之前的一个bug,后续优化。
                        // 服务端更新应用信息，客户端描述内"收起"按钮消失
                        getBinding().includeBody.description.setMaxLines(getResources().getInteger(R.integer.store_app_detail_max_line));

                        getBinding().includeBody.description.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                            @Override
                            public boolean onPreDraw() {
                                final int lines = getBinding().includeBody.description.getLineCount();
                                final int maxLines = getBinding().includeBody.description.getMaxLines();
                                final int ellipsize = getBinding().includeBody.description.getLayout().getEllipsisCount(lines - 1);
                                if (lines < maxLines || (lines == maxLines && ellipsize == 0)) {
                                    getBinding().includeBody.descriptionOpt.setVisibility(View.GONE);
                                } else {
                                    getBinding().includeBody.descriptionOpt.setOnClickListener(view -> {
                                        int currentLines = getBinding().includeBody.description.getLineCount();
                                        if (currentLines == lines) {
                                            getBinding().includeBody.description.setMaxLines(Integer.MAX_VALUE);
                                            getBinding().includeBody.descriptionOpt.setText(R.string.store_des_collapse);
                                        } else {
                                            getBinding().includeBody.description.setMaxLines(maxLines);
                                            getBinding().includeBody.descriptionOpt.setText(R.string.store_des_more);
                                        }

                                    });
                                }
                                getBinding().includeBody.description.getViewTreeObserver().removeOnPreDrawListener(this);
                                return false;
                            }
                        });
                    }
                });
            }
        });
    }


    private void popupUninstallDialog() {
        CommonAlert.showAlertDialog(this, viewModel.appDetail.getValue().getAppName(), getString(R.string.store_uninstall_message), v -> {
            AppPackage.uninstallApk(this, viewModel.appDetail.getValue().getAppSummary().getAppPackageName());
        }, false);
    }

    public class ScreenshotAdapter extends SimpleDataBindingAdapter<String, AppDetailScreenshotBinding> {

        public ScreenshotAdapter() {
            super(AppDetailActivity.this, R.layout.app_detail_screenshot, new DiffUtil.ItemCallback<String>() {
                @Override
                public boolean areItemsTheSame(@NonNull String oldItem, @NonNull String newItem) {
                    return oldItem.equals(newItem);
                }

                @Override
                public boolean areContentsTheSame(@NonNull String oldItem, @NonNull String newItem) {
                    return oldItem.equals(newItem);
                }
            });

            setOnItemClickListener((item, position) -> {
                Intent intent = new Intent(AppDetailActivity.this, PreviewActivity.class);
                intent.putExtra(PreviewActivity.EXTRA_CURRENT_IMAGE, position);
                intent.putStringArrayListExtra(PreviewActivity.EXTRA_IMAGE_URL_LIST, (ArrayList<String>) viewModel.appDetail.getValue().getScreenshots());
                startActivity(intent);
            });
        }

        @Override
        protected void onBindItem(AppDetailScreenshotBinding binding, String item, RecyclerView.ViewHolder holder) {
            binding.setImageUrl(item);
        }

    }

    @BindingAdapter(value = {"imageUrl"})
    public static void loadUrl(ImageView imageView, String image) {
        Glide.with(imageView.getContext())
                .load(image)
                .placeholder(R.drawable.store_ic_preivew_default)
                .into(imageView);
    }

    public class ClickProxy {
        public void cancelDownload() {
            ApkDownloadManager.getInstance().cancelDownload(AppDetailActivity.this, viewModel.appDetail.getValue().getAppId());
        }

        public void rightButtonAction(View view) {
            AppModel appModel = viewModel.appDetail.getValue();
            buttonClick(AppDetailActivity.this, appModel);
        }

        public void leftButtonAction() {
            popupUninstallDialog();
        }

        public void retry() {
            requestWithProgress(appId);
        }

    }
}
